<?php

/**
 * Trida modelu pro obrazky.
 *
 * @author David Dusek
 */
class PictureModel extends NTableSelection {
    public function __construct(NConnection $connection) {
        parent::__construct("picture", $connection);
    }
    
    /**
     * Ulozeni obrazku do databaze a do souboru.
     * @param array $data
     * @return NTableRow nebo FALSE v pripade chyby nebo pocet radku ktere byly
     * zmeneny
     */
    public function insert($data) {
        // ulozeni obrazku do souboru
        $path = Picture::save($data["filename"], $data["data"], $data["estate"]);
        
        if ($path === FALSE) {
            return FALSE;
        }
        
        $data["path"] = $path;        
        unset($data["filename"]);
        unset($data["data"]);
        return parent::insert($data);
    }
    
    /**
     * Provede update zaznamu. Meni pouze zazna v databazi ale nemeni fyzicky
     * soubor obrazku.
     * @param array $data 
     */
    public function update($data) {
        unset($data["filename"]);
        unset($data["data"]);
        
        parent::update($data);
    }
    
    /**
     * Smaze z databaze i fyzicky obrazky pro danou nemovitost, ktere nejsou 
     * uvedeny v poli picturesIds.
     * @param int $estateId Id nemovitosti.
     * @param array $apiPictues 
     */
    public function deleteDiff($estateId, $picturesIds) {
        if (!is_array($picturesIds)) {
            return;
        }
        
        $ids = implode(",", $picturesIds);
        $diff = $this->where("estate", $estateId)->where("id NOT IN ($ids)");
        
        foreach ($diff as $picture) {
            Picture::delete($picture->path);
            $picture->delete();
        }
    }
    
    /**
     * Smazani obrazku vcetne souboru z disku. 
     */
    public function delete() {
        Picture::delete($this->path);
        parent::delete();
    }
}
